package com.sky.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author mr.Nuyoah
 * @Date2025/5/28 17:33
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;


    /**
     * 用户下单
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //1.判断特殊情况(配送地址是否为空,购物车是否为空,配送地址是否超出范围)
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        //1.1如果地址为空则抛异常
        if (addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //TODO
        //检查用户的收获地址是否超出配送范围
        //BaiduUtil.checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        //1.2判断购物车是否存在商品数据
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        //1.2.1如果购物车为空则抛出异常
        if (CollUtil.isEmpty(shoppingCartList)){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2.构建订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);//复制基础属性
        //orders.setId(1L);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//设置订单号,为当前下单时间的时间戳字符串
        orders.setStatus(Orders.PENDING_PAYMENT);//设置订单状态为未支付
        orders.setUserId(userId);//设置下单用户
        orders.setOrderTime(LocalDateTime.now());//设置下单时间
        orders.setPayStatus(Orders.UN_PAID);//设置支付状态为未支付
        orders.setPhone(addressBook.getPhone());//设置手机号
        orders.setAddress(addressBook.getDetail());//设置详细地址
        orders.setConsignee(addressBook.getConsignee());//设置收货人
        orders.setDeliveryTime(dto.getEstimatedDeliveryTime());//设置预计送达时间
        orders.setUserName(addressBook.getConsignee());//设置用户名


        //3.向订单表中添加一条数据
        orderMapper.insert(orders);

        //4.构建订单明细表数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(s->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(s,orderDetail);
            orderDetail.setOrderId(orders.getId());//设置订单单号
            orderDetailList.add(orderDetail);
        });

        //5.向订单明细表中添加多条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //6.清空购物车数据
        shoppingCartMapper.deleteByUserId(userId);

        //7.封装OrderSubmitVO返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();


        return orderSubmitVO;
    }
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        dto.setUserId(BaseContext.getCurrentId());
        List<Orders> ordersList = orderMapper.historyOrders(dto);
        //List<OrderDetail> orderDetailList = new ArrayList<>();
        ordersList.forEach(o->{
            List<OrderDetail> odl = orderDetailMapper.historyOrdersDetail(o.getId());
            o.setOrderDetailList(odl);
        });
        Page<Orders> page = (Page<Orders>) ordersList;
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据id查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public Orders getById(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            // 可以选择抛出异常或者返回空对象，根据业务需求调整
            throw new RuntimeException("订单不存在，ID：" + id); // 或者 return null;
        }
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        orders.setOrderDetailList(orderDetailList);
        return orders;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancel(Long id) {
        //1.查询订单状态
        Orders orders = orderMapper.getById(id);
        //2.判断订单是否可取消
        if (orders==null){
            throw new BaseException("暂无该订单信息,无法取消");
        }
        //3.取消订单
        orderMapper.cancel(id);
        //4.取消订单的订单详情
        orderDetailMapper.cancelBatch(id);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void repetition(Long id) {
        //1.查询当前登录用户
        Long userId = BaseContext.getCurrentId();

        //2.查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //3.将订单详情数据添加到购物车中
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(x, cart, "id");
            cart.setUserId(userId);
            cart.setCreateTime(LocalDateTime.now());
            return cart;
        }).collect(Collectors.toList());

        //4.批量新增购物车数据
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 订单分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult pageList(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //1.分页查询订单数据
        List<Orders> ordersList = orderMapper.pageList(dto);
        //2.根据订单数据获取订单菜品详情数据
        List<OrderVO> orderVOList = new ArrayList<>();
        ordersList.forEach(o->{
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(o,orderVO);//复制基础属性到orderVO
            //2.1获取订单菜品详情数据
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(o.getId());
            //2.2将订单菜品数据转换为订单菜品字符串(以菜品名称和菜品数量拼接)
            List<String> orderDishList = orderDetailList.stream().map(x -> {
                String orderDish = x.getName() + "*" + x.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());
            //2.3将订单菜品字符串数据设置到orderVO中
            orderVO.setOrderDishes(String.valueOf(orderDishList));
            orderVOList.add(orderVO);
        });
        //3.将分页的订单数据封装成分页结果并返回
        Page<Orders> page = (Page<Orders>) ordersList;
        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 统计订单数据
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        //  封装成OrderStatisticsVO并返回
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(ordersConfirmDTO.getStatus())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //1.查询订单
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        //2.判断当前订单是否可拒单,只有状态为待接单的订单才可拒单
        if (orders==null||!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new BaseException("订单不存在或者订单状态不可拒单");
        }

        //3.判断当前订单是否付款，如果已付款则需要退款
        //支付状态
        Integer payStatus = orders.getPayStatus();
        if (payStatus.equals(Orders.UN_PAID)) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    orders.getNumber(),
                    orders.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        //4.更新订单状态为已取消,并设置拒绝原因
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrders(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //  1.查询订单
        Orders orders = orderMapper.getById(id);

        //  2.判断只有状态为待派送的订单才可派送
        if (!orders.getStatus().equals(Orders.CONFIRMED)||orders==null) {
            throw new BaseException("订单不存在或者订单状态不可派送");
        }

        //  3.更新订单状态为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //  1.查询订单
        Orders orders = orderMapper.getById(id);

        // 2.判断只有状态为派送中的订单才可完成
        if (!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)||orders==null) {
            throw new BaseException("订单不存在或者订单状态不可完成");
        }

        //  3.更新订单状态为完成
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }
}
